//
//  EmoticonPackge.swift
//  表情键盘布局
//
//  Created by x on 2017/7/11.
//  Copyright © 2017年 HLB. All rights reserved.
//

/*
 结构:
 
 1.加载emoticons.plist文件得到对应表情的路径
 emoticons.plist(字典) 储存了所有表情的数据
    |-------packge(字典数组)
        |-------id(储存了对应表情的对应的文件夹名字)
 
 2.根据拿到的路径加载对应表情的info.plist文件
 info.plist(字典)
 |-------id(当前表情组文件夹的名称)
 |-------group_name_cn(组的名称)
 |-------emoticons(字典数组)
        |-----chs(表情对应的文字)
        |-----png(表情对应的图片)
        |-----code(emoji表情对应的十六进制字符串)
 */

import UIKit

class EmoticonPackge: NSObject {

    
    /// 当前表情组所在文件夹名称
    var id: String?
    
    /// 当前表情组的名字
    var group_name_cn: String?
    
    /// 当前组对象下面的所有表情
    var emoticons:[Emoticons]?
    
    //1.加载emoticons.plist文件
        //1.1得到Emoticons.bundle的路径
        //1.2得到emoticons.plist的路径
    //2.或emoticons中获取packages
    //3.遍历packages数组
    //4.取出ID创建对应的表情数组
    
    //创建一个静态常量来保证表情只加载一次 ,提高性能
    static let packgeList: [EmoticonPackge] = EmoticonPackge.loadPackages()
    
    //每次进来都要加载一次所有的表情 ,但是表情数据是不变的这样很耗性能
    private class func loadPackages() -> [EmoticonPackge] {
        var emoticonPckages:[EmoticonPackge] = [EmoticonPackge]()
        
        //0.添加最近组
        let pk = EmoticonPackge(id: "")
        pk.group_name_cn = "最近"
        pk.appendEmptyEmoticon()//添加空白按钮
        emoticonPckages.append(pk)
        
        //1.加载emoticons.plist文件(获取某个文件夹下面的某个文件的路径)
        let path = Bundle.main.path(forResource: "emoticons.plist", ofType: nil, inDirectory: "Emoticons.bundle")
        //根据路径得到字典
        let dict = NSDictionary(contentsOfFile: path!)
        let dicArray = dict!["packages"] as! [[String: AnyObject]]
        
        //2.或emoticons中获取packages
        for dic in dicArray {
            let emoticonP = EmoticonPackge(id: dic["id"]! as! String)
            emoticonPckages.append(emoticonP)
            //加载当前组下面多有表情
            emoticonP.loadEmoticons()
            
            //添加空白按钮
            emoticonP.appendEmptyEmoticon()
        }
        return emoticonPckages
    }
    
    /// 加载表情
    private func loadEmoticons() -> Void {
        //1.加载表情组中info.plist
        let dic = NSDictionary(contentsOfFile: infoPath(fileName: "info.plist"))
        group_name_cn = dic!["group_name_cn"] as? String
        let dicArray = dic?["emoticons"] as! [[String: String]]
        emoticons = [Emoticons]()
        //标记是第几个表情
        var index = 0
        
        for dict in dicArray {
            //每一页都添加一个删除按钮
            if index == 20 {
                emoticons?.append(Emoticons(isRemoveBtn: true))
                index = 0
            }
            emoticons?.append(Emoticons(dic: dict, id: id!))
            index += 1
        }
        
    }
    
    /// 添加空白按钮(如果一页不足21个 ,就添加空白按钮补齐)
    private func appendEmptyEmoticon() -> Void {
        
        if emoticons == nil {
            emoticons = [Emoticons]()
        }
        
        let count = emoticons!.count % 21
        //1.添加空白按钮
        for _ in count..<20 {
            emoticons?.append(Emoticons(isRemoveBtn: false))
        }
        
        //2.添加删除按钮
        emoticons?.append(Emoticons(isRemoveBtn: true))
        
    }
    
    /// 添加最近表情
    ///
    /// - Parameter emoticon: <#emoticon description#>
    func appendEmoticons(emoticon: Emoticons) -> Void {
        //1.判断是不是删除那妞
        if emoticon.isRemoveBtn {
            return
        }
        
        //2判断最近中有没有这个表情
        let contains = emoticons!.contains(emoticon)
        if !contains {
            //删除删除按钮
            emoticons?.removeLast()
            
            emoticons?.append(emoticon)
        }
        var result = emoticons?.sorted(by: { (e1, e2) -> Bool in
            return e1.counts > e2.counts
        })
        if !contains {
            //删除多余的按钮
            result!.removeLast()
            //添加上删除按钮
            result!.append(Emoticons(isRemoveBtn: true))
        }
        
        emoticons = result
        
    }
    /// 得到表情的路径
    ///
    /// - Parameter fileName: <#fileName description#>
    /// - Returns: <#return value description#>
    func infoPath(fileName:String) -> String {
        return ((EmoticonPackge.bundlePath() as NSString).appendingPathComponent(id!) as NSString).appendingPathComponent(fileName)
    }
    
    /// 得到微博表情主路径
    ///
    /// - Returns: <#return value description#>
    class func bundlePath() -> String {
        return (Bundle.main.bundlePath as NSString).appendingPathComponent("Emoticons.bundle")
    }
    
    init(id: String) {
        super.init()
        self.id = id
    }
}


class Emoticons: NSObject {
    
    /// 表情对应的文字
    var chs: String?
    
    /// 当前表情对应的文字
    var png: String? {
        didSet {
            //表情图片的全路径
            emoticonPath = ((EmoticonPackge.bundlePath() as NSString).appendingPathComponent(id!) as NSString).appendingPathComponent(png!)
        }
    }
    
    /// 当前表情对应的十六进制的字符串
    var code: String? {
        didSet {
            //1.创建一个扫描
            let scanner = Scanner(string: code!)
            
            //2.将十六进制转换成为emoji表情字符串
            var result:UInt32 = 0
            scanner.scanHexInt32(&result)
            let emoji = Character(UnicodeScalar(result)!)
            emoticonStr = "\(emoji)"
        }
    }
    
    /// 当前表情所在的组的id
    var id: String?
    
    /// 保存图片表情的地址
    var emoticonPath:String?
    
    /// 保存十六进制字符串的表情字符串
    var emoticonStr: String?
    
    /// 标记是否是删除按钮
    var isRemoveBtn: Bool = false
    
    /// 保存表情选中的次数
    var counts: Int = 0
    
    
    /// 一个创建删除按钮的init方法
    ///
    /// - Parameter isRemoveBtn: <#isRemoveBtn description#>
    init(isRemoveBtn: Bool) {
        super.init()
        self.isRemoveBtn = isRemoveBtn
    }

    init(dic:[String: String], id: String) {
        super.init()
        self.id = id
        setValuesForKeys(dic)
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        //print("key====",key)
    }
    
    let tt = ["chs","png","id","emoticonPath","emoticonStr","isRemoveBtn"]
    override var description: String {
        let dic = dictionaryWithValues(forKeys: tt)
        return "\(dic)"
    }
}










